import Mock from 'mockjs'
import { param2Obj } from '@/utils'
import user from './user'

// const mocks = [
//     ...user
// ]
//
// export function mockXHR() {
//     Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
//     Mock.XHR.prototype.send = function() {
//         if (this.custom.xhr) {
//             this.custom.xhr.withCredentials = this.withCredentials || false
//
//             if (this.responseType) {
//                 this.custom.xhr.responseType = this.responseType
//             }
//         }
//         this.proxy_send(...arguments)
//     }
//
//     function XHR2ExpressReqWrap(respond) {
//         return function(options) {
//             console.log("XHR2ExpressReqWrap-function :" + options)
//             let result = null
//             if (respond instanceof Function) {
//                 const { body, type, url } = options
//                 result = respond({
//                     method: type,
//                     body: JSON.parse(body),
//                     query: param2Obj(url)
//                 })
//             } else {
//                 result = respond
//             }
//             return Mock.mock(result)
//         }
//     }
//
//     for (const i of mocks) {
//         Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
//     }
// }

import query from 'querystring'

const get = url => {
    const host = 'http://' + location.host + '/'
    const arg = new URL(url, host)
    const api = arg.pathname
    const params = query.parse(arg.search.slice(1))
    return { api, params }
}

const post = (url, body) => {
    const api = url
    const params = JSON.parse(body)
    return { api, params }
}

export function mockXHR() {
    Mock.mock(RegExp('/api/.*'), res => {
        const arg = (res.type === 'GET') ? get(res.url) : post(res.url, res.body)
        // window.console.log(arg)

        const moduleFiles = require.context('./modules', false, /\.js$/)
        const service = moduleFiles.keys().reduce((service, modulePath) => {
            const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
            service[moduleName] = moduleFiles(modulePath).default
            return service
        }, {})
        const apiName = arg.api.replace(/^\/api\/(.*)$/, '$1')
        const program = service[apiName]
        // console.log(Object.entries(res))   // XXX:
        if (program) {
            return program(arg.params)
        } else {
            return {
                code: 0,
                msg: 'there is no api for ' + apiName
            }
        }
        // window.console.log(service)
    })
}
